package com.gitee.zhuyb.controller;

import com.gitee.zhuyb.poi.FreemarkerUtil;
import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.Units;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0.0
 * @Description: #类描述
 * @Date: 2021/12/25 12:03
 * @Copyright (C) ZhuYouBin
 */
@Service
public class ExportService implements IExportService {

    @Override
    public void exportWord(HttpServletResponse response) throws Exception {

        String templatePath = "G:\\zhuyoubin_gitee_space\\code\\work-demo\\poi-word\\src\\main\\resources\\";
        String templateName = "demo模板.ftl";
        String fileName = "response.doc";
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("image", "");

        // 获取配置类
        Configuration cfg = new Configuration();
        // 指定模板加载器
        File file = new File(templatePath);
        FileTemplateLoader ftl = new FileTemplateLoader(new File(file.getAbsolutePath()));
        // 设置模板加载器
        cfg.setTemplateLoader(ftl);
        // 获取模板文件
        Template template = cfg.getTemplate(templateName, "UTF-8");

        // 获取流
        // 告诉浏览器用什么软件可以打开此文件
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        Writer writer = response.getWriter();
        // 处理文件
        template.process(dataModel, writer);
    }

    @Override
    public void exportWordByPoi(HttpServletResponse response) throws Exception {
        String fileName = "response.doc";
        // 告诉浏览器用什么软件可以打开此文件
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));

        // 输出
        OutputStream out = response.getOutputStream();

        XWPFDocument document = this.createWord();
        document.write(out);
        out.close();
    }

    private XWPFDocument createWord() throws Exception {
        XWPFDocument document = new XWPFDocument();
            String[] categories = new String[]{"Lang 1", "Lang 2", "Lang 3"};
            Double[] valuesA = new Double[]{10d, 20d, 30d};
            Double[] valuesB = new Double[]{15d, 25d, 35d};

            XWPFChart chart = document.createChart(15 * Units.EMU_PER_CENTIMETER, 10 * Units.EMU_PER_CENTIMETER);

            int numOfPoints = categories.length;
            String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 0, 0));
            String valuesDataRangeA = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1));
            String valuesDataRangeB = chart.formatRange(new CellRangeAddress(1, numOfPoints, 2, 2));
            XDDFDataSource<String> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
            XDDFNumericalDataSource<Double> valuesDataA = XDDFDataSourcesFactory.fromArray(valuesA, valuesDataRangeA, 1);
            XDDFNumericalDataSource<Double> valuesDataB = XDDFDataSourcesFactory.fromArray(valuesB, valuesDataRangeB, 2);

            XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
            XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
            leftAxis.setCrossBetween(AxisCrossBetween.BETWEEN);

            // create chart data
            XDDFChartData data = chart.createData(ChartTypes.BAR, bottomAxis, leftAxis);
            ((XDDFBarChartData) data).setBarDirection(BarDirection.COL);

            ((XDDFBarChartData) data).setVaryColors(false);
            XDDFChartData.Series series = data.addSeries(categoriesData, valuesDataA);
            series.setTitle("a", setTitleInDataSheet(chart, "a", 1));

            chart.plot(data);

            // create legend
            XDDFChartLegend legend = chart.getOrAddLegend();
            legend.setPosition(LegendPosition.LEFT);
            legend.setOverlay(false);

            return document;
    }

    private CellReference setTitleInDataSheet(XWPFChart chart, String title, int column) throws Exception {
        XSSFWorkbook workbook = chart.getWorkbook();
        XSSFSheet sheet = workbook.getSheetAt(0);
        XSSFRow row = sheet.getRow(0);
        if (row == null)
            row = sheet.createRow(0);
        XSSFCell cell = row.getCell(column);
        if (cell == null)
            cell = row.createCell(column);
        cell.setCellValue(title);
        return new CellReference(sheet.getSheetName(), 0, column, true, true);
    }

}
